package com.wswy.wzcx.module;

import android.Manifest.permission;
import android.content.Context;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import com.blankj.utilcode.util.PermissionUtils;
import com.che.common.map.LocationLoader;
import com.che.common.map.LocationLoader.OnLocationCallback;
import com.che.common.map.LocationModel;
import com.che.libcommon.utils.JsonKit;
import com.che.libcommon.utils.RxBus;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.wswy.wzcx.jpush.PushChannel;
import com.wswy.wzcx.model.WZCity;
import com.wswy.wzcx.model.core.PreLoader;
import com.wswy.wzcx.utils.Tools;
import io.reactivex.observers.ResourceObserver;
import timber.log.Timber;

public class LocManager {

  private static final String TAG = "LocManager";

  private static final String LAST_LOCATION = "user_loc_cache";
  private static final String LAST_CHOOSE_CITY = "user_choose_city";

  private static class InstanceHolder{
    private static final LocManager holder = new LocManager();
  }

  public static LocManager getInstance(){

    return InstanceHolder.holder;
  }


  private Context context;

  //当前定位
  private LocationModel currentLocation;
  //当前选择的位置
  private WZCity currentWZCity;

  private boolean isLoading = false;

  private boolean useDefault = false;

  private LocManager() {
  }

  public LocManager init(Context context){
    this.context = context;

    return this;
  }

  public boolean hasPermission(){
    return PermissionUtils.isGranted(permission.ACCESS_FINE_LOCATION);
  }

  public boolean isLoading() {
    return isLoading;
  }


  public void requestAndLoad(FragmentActivity activity,final OnRequestLocationCallback callback){
    new RxPermissions(activity).request(permission.ACCESS_FINE_LOCATION).subscribe(
        new ResourceObserver<Boolean>() {
          @Override
          public void onNext(Boolean aBoolean) {
            if (aBoolean){
              loadLocation(callback);
            }else {
              //请求拒绝
              if (callback != null){
                callback.onError("没有权限");
              }
            }

          }

          @Override
          public void onError(Throwable e) {

          }

          @Override
          public void onComplete() {

          }
        });
  }

  public void loadLocation(){
    loadLocation(null);
  }


  private void loadLocation(final OnRequestLocationCallback callback){
    getCurrentWZCity();
    if(!isLoading && PermissionUtils.isGranted(permission.ACCESS_FINE_LOCATION)) {
      isLoading = true;
      LocationLoader.load(context, new OnLocationCallback() {
        @Override
        public void onLoaded(LocationModel locationModel) {
          isLoading = false;
          if(locationModel != null && !TextUtils.isEmpty(locationModel.province)){
            currentLocation = locationModel;

            Tools.getCache().put(LAST_LOCATION,JsonKit.GSON.toJson(locationModel));

            Timber.e("gps load -->"+locationModel);

            WZCity byAdCode = GlobalConfigManager.getInstance().getCityManager()
                .findByAdCode(locationModel.adCode);

            Timber.e("local find -->"+byAdCode);

            if (callback != null){
              callback.onGetLocation(locationModel);
            }

            onGetLoc(byAdCode);
          }
        }
      });

    }
  }




  private void onGetLoc(WZCity model){
    if (useDefault){
      saveWZCity(model);
      RxBus.getDefault().postWithCode(InternalMsgCode.CODE_GET_LOCATION,model);
    }

  }

  private LocationModel getFromCache(){
    String json = Tools.getCache().getString(LAST_LOCATION);
    if (!TextUtils.isEmpty(json)){
      try {
        return JsonKit.GSON.fromJson(json,LocationModel.class);
      }catch (Throwable e){
        Tools.getCache().remove(LAST_LOCATION);
        e.printStackTrace();
      }
    }
    return null;
  }

  private WZCity loadCurrentWZCity(){
    String json = Tools.getCache().getString(LAST_CHOOSE_CITY);
    if (!TextUtils.isEmpty(json)){
      try {
        return JsonKit.GSON.fromJson(json,WZCity.class);
      }catch (Throwable e){
        Tools.getCache().remove(LAST_CHOOSE_CITY);
        e.printStackTrace();
      }
    }
    return null;
  }

  public LocationModel getCurrentLocation() {
    if (currentLocation == null){
      currentLocation = getFromCache();
    }
    return currentLocation;
  }

  public
  WZCity getCurrentWZCity(){
    if (currentWZCity == null){
      currentWZCity = loadCurrentWZCity();
    }
    if (currentWZCity == null){
      currentWZCity = WZCity.DEFAULT;
      useDefault = true;
    }
    return currentWZCity;
  }


  public void saveWZCity(@NonNull WZCity city) {
    //保存结果
    Tools.getCache().put(LAST_CHOOSE_CITY, JsonKit.GSON.toJson(city));

    final WZCity oldCity = currentWZCity;
    currentWZCity = city;

    if (oldCity == null || !TextUtils.equals(oldCity.name, city.name)) {
      //更新天气
      WeatherManager.getInstance().loadWeather(city.name);
      PushChannel.getPushTagManager().updateTags();

      if (oldCity != null) {
        PreLoader.reloadTabs();
      }

    }

  }

  public void distanceBetween(double endLatitude, double endLongitude,float[] results){
    if(currentLocation != null){
      Location.distanceBetween(currentLocation.latitude,currentLocation.longitude,endLatitude,endLongitude,results);
    }
  }

  public void lazyLoad(){
    if(currentLocation == null){
      loadLocation();
    }
  }

  public String getDisplayCityName(){
    WZCity wzCity = getCurrentWZCity();
    if (wzCity != null){
      return wzCity.name;
    }
    LocationModel location = getCurrentLocation();
    if (location != null){
      return location.city;
    }
    return "";
  }

  public interface OnRequestLocationCallback{

    void onGetLocation(LocationModel locationModel);

    void onError(String msg);

  }

}
